#!/bin/sh

# kernel version must be supplied
[ $# -lt 1 -o -z "$1" ] && exit 0

set -e

do_backup() {
    [ ! -f "/boot/$1" ] && return 0
    tgtn="/boot/.apk-backup.$1"
    # if an existing backup already exists, skip it
    [ -f "$tgtn" ] && return 0
    mv "/boot/$1" "${tgtn}"
}

backup_kernel() {
    # try names that may be worth backing up, not all may exist
    do_backup "vmlinux-$1"
    do_backup "vmlinuz-$1"
    do_backup "initramfs-$1.img"
    do_backup "initrd.img-$1"
    do_backup "config-$1"
    do_backup "System.map-$1"
}

backup_modules() {
    # must exist as a directory
    [ -d "/usr/lib/modules/$1" ] || return 0

    # must not have an existing backup in any form
    [ -e "/usr/lib/modules/apk-backup/$1" ] && return 0

    mv "/usr/lib/modules/$1" "/usr/lib/modules/apk-backup/$1"
}

mkdir -p /usr/lib/modules/apk-backup || exit 1

backup_kernel "$1"
backup_modules "$1"
